<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'
import ShowPlan from './ShowPlan.vue'
import { listByUserSelect } from '@/utils/format'
import type { PickerConfirmEventParams } from 'vant'
import { getStringToNumber } from '@/utils'
import { useUserStore } from '@/stores/user'
import { getUserFilterUtil, createUserFiltersUtil } from '@/AGC/utils/user_filters'
import type { UserFiltersI } from '@/types/user'
import dayjs from 'dayjs'

const store = useUserStore()
const userFilter = ref<UserFiltersI | undefined>(store.userFilter)
// 获取用户筛选条件
const getUserFilter = async () => {
  try {
    if (userFilter.value == undefined) {
      userFilter.value = await getUserFilterUtil(store.userInfo.id)

      if (userFilter.value) {
        store.setUserFilter(userFilter.value)
      }
    }
  } catch (error) {
    Promise.reject(error)
  }
}
getUserFilter()
// const isPlan = ref(false)
const isStart = ref(false) // false: 未开始 true：开始
const steps = ref(0) // 0：收集用户的基本信息 1：收集用户的生活习惯 2：展示计划
// 基本信息表单实例
const basicFormRef = ref()
// 基本信息表单数据
const basicFormModel = ref({
  target: 0,
  sex: 0,
  age: '',
  height: '',
})
const basicFormRules = {
  target: [{ required: true, message: '请选择目标', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请选择年龄', trigger: 'change' }],
  height: [{ required: true, message: '请选择身高', trigger: 'change' }],
}
// 生活习惯表单数据
const habitFormRef = ref()
const habitFormModel = ref({
  weight: '',
  targetWeight: '',
  sportAbility: 1.375,
  eatScene: 0,
})
const habitFormRules = {
  weight: [{ required: true, message: '请选择体重', trigger: 'change' }],
  targetWeight: [
    { required: true, message: '请选择目标体重', trigger: 'change' },
    {
      validator: (rule: unknown, value: string, callback: (error?: Error) => void) => {
        const tempWeight = getStringToNumber(habitFormModel.value.weight, 'k')
        const tempValue = getStringToNumber(value, 'k')

        if (basicFormModel.value.target == 0) {
          if (tempWeight < tempValue) {
            callback()
          } else {
            callback(new Error('目标体重需要大于当前体重'))
          }
        } else {
          if (tempValue < tempWeight) {
            callback()
          } else {
            callback(new Error('目标体重需要小于当前体重'))
          }
        }
      },
    },
  ],
  sportAbility: [{ required: true, message: '请选择运动能力', trigger: 'change' }],
  eatScene: [{ required: true, message: '请选择吃东西场景', trigger: 'change' }],
}
// 下一步点击事件
const nextStep = async () => {
  await basicFormRef.value.validate()
  steps.value++
}
// 提交筛选条件
const onSubmit = async () => {
  await habitFormRef.value.validate()
  // 发送请求
  const { weight, targetWeight, sportAbility, eatScene } = habitFormModel.value
  const { target, sex, age, height } = basicFormModel.value
  userFilter.value = {
    user_id: store.userInfo.id,
    target,
    sex,
    age,
    height,
    weight,
    target_weight: targetWeight,
    sport_ability: sportAbility,
    eat_scene: eatScene,
    date: dayjs().format('YYYY-MM-DD'),
  }

  try {
    store.setUserFilter(userFilter.value)
    await createUserFiltersUtil(userFilter.value)
    steps.value++
    ElMessage.success('提交成功')
  } catch (error) {
    userFilter.value = undefined
    ElMessage.error('提交失败')
    Promise.reject(error)
  }
}
// Picker 显示数据
const columns = ref<{ text: string; value: string }[]>([])
const weightColumns = ref<{ text: string; value: string }[][]>([])
// Picker 显示类型
const showPopupType = ref<string>('')
// 监听 picker显示类型
watch(showPopupType, (value) => {
  if (value) {
    if (listByUserSelect(value) != undefined) {
      if (value == 'weight' || value == 'targetWeight') {
        weightColumns.value = listByUserSelect(value)! as { text: string; value: string }[][]
      } else {
        columns.value = listByUserSelect(value)! as { text: string; value: string }[]
      }
    }
  }
})
// Picker 确认事件
const onConfirm = ({ selectedValues }: PickerConfirmEventParams) => {
  switch (showPopupType.value) {
    case 'age':
      basicFormModel.value.age = selectedValues[0].toString()
      break
    case 'height':
      basicFormModel.value.height = selectedValues[0].toString()
      break
    case 'weight':
      habitFormModel.value.weight = selectedValues[0] + '.' + selectedValues[1] + 'kg'
      break
    case 'targetWeight':
      habitFormModel.value.targetWeight = selectedValues[0] + '.' + selectedValues[1] + 'kg'
      break
  }
  showPopupType.value = ''
}
</script>

<template>
  <el-button
    style="font-size: 50px"
    type="text"
    class="start"
    @click="isStart = true"
    v-if="userFilter == undefined && isStart == false"
    >开始定制计划
  </el-button>
  <div v-else-if="userFilter == undefined && isStart == true" class="plan">
    <!-- 步骤条 -->
    <el-steps direction="vertical" :active="steps" class="step">
      <el-step title="基本信息" />
      <el-step title="生活习惯" />
    </el-steps>
    <div style="margin-top: 5%">
      <!-- 第一步 -->
      <el-form
        label-width="100px"
        class="form"
        v-show="steps == 0"
        :model="basicFormModel"
        ref="basicFormRef"
        :rules="basicFormRules"
      >
        <el-form-item label="目标:" prop="target" class="MyRadio">
          <el-radio-group v-model="basicFormModel.target" name="target">
            <el-radio :value="0">增重</el-radio>
            <el-radio :value="1">减脂</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别:" prop="sex" class="MyRadio">
          <el-radio-group v-model="basicFormModel.sex" name="sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄:" prop="age">
          <div>
            <van-field
              v-model="basicFormModel.age"
              is-link
              readonly
              placeholder="请选择年龄"
              @click="showPopupType = 'age'"
            />
            <van-popup :show="showPopupType == 'age'" round position="center">
              <van-picker :columns="columns" @cancel="showPopupType = ''" @confirm="onConfirm" />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="身高:" prop="height">
          <div>
            <van-field
              v-model="basicFormModel.height"
              is-link
              readonly
              placeholder="请选择身高"
              @click="showPopupType = 'height'"
            />
            <van-popup :show="showPopupType == 'height'" round position="center">
              <van-picker :columns="columns" @cancel="showPopupType = ''" @confirm="onConfirm" />
            </van-popup>
          </div>
        </el-form-item>
      </el-form>
      <!-- 第二步 -->
      <el-form
        label-width="100px"
        class="form"
        v-show="steps == 1"
        :model="habitFormModel"
        ref="habitFormRef"
        :rules="habitFormRules"
      >
        <el-form-item label="当前体重:" prop="weight">
          <div>
            <van-field
              v-model="habitFormModel.weight"
              is-link
              readonly
              placeholder="请选择当前体重(kg)"
              @click="showPopupType = 'weight'"
            />
            <van-popup :show="showPopupType == 'weight'" round position="center">
              <van-picker
                :columns="weightColumns"
                @cancel="showPopupType = ''"
                @confirm="onConfirm"
              />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="目标体重:" prop="targetWeight">
          <div>
            <van-field
              v-model="habitFormModel.targetWeight"
              is-link
              readonly
              placeholder="请选择目标体重(kg)"
              @click="showPopupType = 'targetWeight'"
            />
            <van-popup :show="showPopupType == 'targetWeight'" round position="center">
              <van-picker
                :columns="weightColumns"
                @cancel="showPopupType = ''"
                @confirm="onConfirm"
              />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="运动能力:" prop="sportAbility" class="MyRadio">
          <el-radio-group v-model="habitFormModel.sportAbility" name="sportAbility">
            <el-radio :value="1.375">从未锻炼</el-radio>
            <el-radio :value="1.55">偶尔锻炼</el-radio>
            <el-radio :value="1.725">经常锻炼</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用餐场景:" prop="eatScene" class="MyRadio">
          <el-radio-group v-model="habitFormModel.eatScene" name="eatScene">
            <el-radio :value="0">食堂</el-radio>
            <el-radio :value="1">家</el-radio>
            <el-radio :value="2">外卖</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 步骤控制 -->
      <div
        :style="{
          'margin-left': steps == 0 ? '45%' : '40%',
          'margin-top': steps == 0 ? '5%' : '10%',
        }"
      >
        <el-button v-show="steps == 1" @click="steps--">上一步</el-button>
        <el-button type="primary" v-show="steps == 0" @click="nextStep">下一步</el-button>
        <el-button type="primary" v-show="steps == 1" @click="onSubmit">提交</el-button>
      </div>
    </div>
  </div>
  <ShowPlan v-else-if="userFilter != undefined"></ShowPlan>
</template>

<style scoped lang="less">
.start {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.plan {
  display: flex;
  flex: 1;
  padding: 20px;
  background-color: rgb(247, 248, 250);

  .step {
    margin-top: 100px;
    margin-left: 50px;
    height: 200px;
    width: 180px;
  }

  .form {
    width: 700px;
    margin-top: 12%;
    margin-left: 23%;

    .el-form-item {
      width: 80%;
      margin-bottom: 20px;

      ::v-deep(.el-form-item__label) {
        padding: 6px 12px 0 0;
      }

      .van-popup {
        width: 30%;
      }
    }

    .MyRadio {
      ::v-deep(.el-form-item__label) {
        padding: 0 12px 0 0;
      }
    }
  }
}
</style>
